package com.fu.exception;

import com.fu.config.TokenCache;
import com.fu.response.RestResult;
import com.fu.utils.CheckUtils;
import com.fu.utils.Constants;
import com.fu.utils.RestResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Project : rest-server
 * @Package Name : com.fu.exception
 * @Description : 校验 Advice
 * @author : Little Ant
 * @Creation Date : 2017年 11月 01日 15:30
 * @ModificationHistory who      when        what
 * -------  -----------  ------------------------------
 */
@ControllerAdvice
public class ValidationControllerAdvice {

    /**
     * 不予拦截的请求地址列表
     */
    private static List<String> IGNORE_URL_LIST = new ArrayList<>();

    private static final String TOKEN = "token";

    static {
        // 类初始化时添加信任地址列表
        IGNORE_URL_LIST.add("/api/v1.0/auth/token");
    }

    @Autowired
    TokenCache tokenCache;

    @ModelAttribute
    public HttpServletRequest getRequest(HttpServletRequest request) throws UnsupportedEncodingException,ValidateException{
        String url = request.getRequestURI();
        String result = CheckUtils.requestCheck(request);
        if (IGNORE_URL_LIST.contains(url)){
            return request;
        }
        if (result.equals(Constants.INVALID_REQUEST_PARAMATERS)){
            throw new ValidateException(Constants.INVALID_REQUEST_PARAMATERS,"token或timestamp或sign参数不能为空");
        }
        if (result.equals(Constants.REQUEST_OUT_OF_TIME)){
            throw new ValidateException(Constants.REQUEST_OUT_OF_TIME,"请求超时,请重新发送请求");
        }
        if (!tokenCache.exist(request.getParameter(TOKEN))){
            throw new ValidateException(Constants.INVALID_TOKEN,"无效的token参数");
        }
        if (result.equals(Constants.INVALID_SIGN)){
            throw new ValidateException(Constants.INVALID_SIGN,"无效的sign参数");
        }
        return request;
    }

    @ExceptionHandler({ValidateException.class})
    @ResponseBody
    public RestResult validateException(ValidateException re){
        return RestResultUtils.genErrorResult(re.getErrorCode(),re.getMessage());
    }
}
